import Vue from "vue";
import Axios from "axios";
// import copy from 'copy-to-clipboard';
import json = Mocha.reporters.json;

// let md5 = require('md5');
// let md5 = require('md5');
// let Qs = require('qs');

interface headerObject {
    version: string,
    token: any | null,
    type: string,
    noncestr: string,
    did: string,
    sign: string,
    'Content-Type': string
}

export default class Sence extends Vue {
    public apiurl: string = 'http://erp.anyyun.cn/'; // 域名配置
    // public apiurl: string = '../'; // 域名配置
    public pageSize: number = 10; // 页面记录数配置
    constructor() {
        super();
        if (process.env.NODE_ENV === 'development') {
            this.apiurl = '/site';
        }
    }

    public api: any = {
        key: 'CYW2019ANYIDC',
    }; // 系统配置参数


    public apihead: headerObject = {
        version: '1.1',
        token: '',
        type: 'wap',
        noncestr: '',
        did: '',
        sign: '',
        'Content-Type': 'text/html; charset=utf-8',
    }; // 接口头配置参数

    public apiheader(): object {  // 接口头数据处理
        const md5 = require('md5');
        this.apihead.token = this.getuser() ? this.getuser().token : localStorage.getItem('token') ? localStorage.getItem('token') : '';
        this.apihead.noncestr = md5(Date.parse(new Date().toString()).toString());
        this.apihead.did = Date.parse(new Date().toString()).toString();
        this.apihead.sign = md5(md5('did=' + this.apihead.did + '&noncestr=' + this.apihead.noncestr + '&token=' + this.apihead.token + '&type=' + this.apihead.type + '&version=' + this.apihead.version) + this.api.key);
        return this.apihead;
    }

    public get(url: string, obj: any = {}): any {
        let promise: object = new Promise((resolve, reject) => {
            Axios.get(this.apiurl + url, {headers: this.apiheader(), params: obj}).then(res => {
                resolve(res.data);
            })
                .catch(err => {
                    reject(err);
                });
        });
        return promise;
    }

    public post(url: string, obj: any = {}): any {
        obj.token=localStorage.getItem('token')?localStorage.getItem('token'):'';
        let promise: object = new Promise((resolve, reject) => {
            Axios.post(this.apiurl + url, obj)
                .then(res => {
                    if (res.data.status == 1) {
                        resolve(res.data);
                    } else if (res.data.status == 509) {
                        localStorage.removeItem('user');
                        this.$router.push('/mine');
                    } else {
                        (<any> this).$createDialog({
                            type: 'alert',
                            title: '提示',
                            content: res.data.message,
                            icon: 'cubeic-alert',
                        }).show();
                        // this.toast(res.data.message,'warn');
                    }
                })
                .catch(err => {
                    reject(err);
                });
        });
        return promise;
    }

    public GetRequest(url: string): any {
        var theRequest: any = {};
        if (url.indexOf('?') != -1) {
            var str: any = url.substring(url.indexOf('?') + 1);
            // console.log(str);
            let strs: any = str.split('&');
            // console.log(strs);
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
            }
        }
        return theRequest;
    }

    // 信息弹出框
    public toast(txt: string, type: string = 'correct'): void {
        const toast = (<any> this).$createToast({
            txt,
            type,
        });
        toast.show();
    }

    // 存缓存
    public set(key: string, data: any): void {
        localStorage.setItem(key, JSON.stringify(data));
    }

    // 取用户缓存
    public getuser(): any {
        let user: any = localStorage.getItem('user');
        return JSON.parse(user);
    }

    // 更新用户信息
    public freshUser(): any {
        let promise: object = new Promise((resolve, reject) => {
            this.post('index.php/api/Users/info').then((res: any) => {
                // this.set('user', res.data.userInfo);
                resolve(res.data);
            });
        });
        return promise;
    }

    // // 复制
    // public copy(data: string): void {
    //     copy(data);
    // }


    // 显示加载
    public showLoading(): void {
        (<any> this).$createToast({
            txt: 'Loading...',
            mask: true,
            time: 10000,
        }).show();
    }


    // 隐藏加载
    public hideLoading(): void {
        (<any> this).$createToast({}).hide();
    }

    // 前往认证经销商
    public goToDealer(): void {
        const user = this.getuser();
        console.log(user);
        if (user.apply&&user.apply.auth_status == 0) {
            (<any> this).$createDialog({
                type: 'alert',
                title: '提示',
                content: '您已提交认证资料，请耐心等待审核，谢谢！',
                icon: 'cubeic-alert',
            }).show();
        } else {
            (<any> this).$createDialog({
                type: 'confirm',
                icon: 'cubeic-alert',
                title: '提示',
                content: '请先认证经销商！',
                confirmBtn: {
                    text: '确定',
                    active: true,
                    disabled: false,
                    href: 'javascript:;',
                },
                cancelBtn: {
                    text: '取消',
                    active: false,
                    disabled: false,
                    href: 'javascript:;',
                },
                onConfirm: () => {
                    this.$router.push('/cardealer');
                },
                onCancel: () => {
                },
            }).show();
        }

    }

    // 前往登录
    public goToLogin(): void {
        (<any> this).$createDialog({
            type: 'confirm',
            icon: 'cubeic-alert',
            title: '提示',
            content: '请先登录！',
            confirmBtn: {
                text: '确定',
                active: true,
                disabled: false,
                href: 'javascript:;',
            },
            cancelBtn: {
                text: '取消',
                active: false,
                disabled: false,
                href: 'javascript:;',
            },
            onConfirm: () => {
                this.$router.push('/mine');
            },
            onCancel: () => {
            },
        }).show();
    }
}
